<template>
  <div class="course-section">
    <el-card>
      <div slot="header">
        <span>{{ $route.query.courseName }}</span>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="dialogVisible=true">
          添加阶段
        </el-button>
      </div>
      <el-tree
        :data="sections"
        :props="defaultProps"
        draggable
        :allow-drop="handleAllowDrop"
        @node-drop="handleNodeDrop">
        <div class="inner" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span v-if="data.sectionName" class="action">
            <el-button @click="handleEditSection(data)">编辑</el-button>
            <el-button @click="handleAddLesson(data, node)">添加课时</el-button>
            <el-button>状态</el-button>
          </span>
          <span v-else class="action">
            <el-button @click="handleEditLesson(data, node)">编辑</el-button>
            <el-button
              @click="$router.push({
                name: 'courseVideo',
                params: {
                  courseId
                },
                query: {
                  lessonId: data.id
                }
              })"
            >上传视频</el-button>
            <el-button>状态</el-button>
          </span>
        </div>
      </el-tree>
    </el-card>
    <!-- 添加编辑章节信息 -->
    <el-dialog
      title="章节信息"
      :visible.sync="dialogVisible"
      width="50%">
      <el-form :model="sectionForm">
        <el-form-item label="课程信息">
          <el-input v-model="$route.query.courseName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="章节名称">
          <el-input v-model="sectionForm.sectionName"></el-input>
        </el-form-item>
        <el-form-item label="章节描述">
          <el-input v-model="sectionForm.description"></el-input>
        </el-form-item>
        <el-form-item label="章节排序">
          <el-input-number
            v-model="sectionForm.orderNum"
            :min=1
            controls-position="right"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleAddSection">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加编辑课时信息 -->
    <el-dialog
      title="课程名称"
      :visible.sync="LessondialogVisible"
      width="50%">
      <el-form :model="lessonForm">
        <el-form-item label="课程名称">
          <el-input
            v-model="$route.query.courseName"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="章节名称">
          <el-input
            v-model="lessonForm.sectionName"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="课时名称">
          <el-input v-model="lessonForm.theme"></el-input>
        </el-form-item>
        <el-form-item label="时长">
          <el-input
            v-model="lessonForm.duration">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否放开试听">
          <el-switch v-model="lessonForm.isFree"></el-switch>
        </el-form-item>
        <el-form-item label="课时顺序">
          <el-input v-model="lessonForm.orderNum">
            <template slot="append">数字控制顺序，数字越大越靠后</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="LessondialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSaveLesson(data)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSectionAndLesson,
  saveOrUpdateSection,
  saveOrUpdateLesson
  // getBySectionId
} from '@/services/courseSection'
export default {
  name: 'CourseSection',
  props: {
    courseId: {
      type: [Number, String],
      required: true
    }
  },
  created () {
    this.loadCourseSection()
  },
  data () {
    return {
      sections: [],
      sectionForm: {
        courseId: this.courseId,
        courseName: this.$route.query.courseName,
        sectionName: '',
        description: '',
        orderNum: 0
      },
      lessonForm: {
        courseId: this.courseId,
        courseName: this.$route.query.courseName,
        sectionId: 0,
        sectionName: '',
        theme: ' ',
        duration: 0,
        isFree: true,
        orderNum: 0,
        status: 0
      },
      defaultProps: {
        children: 'lessonDTOS',
        label (data) {
          return data.sectionName || data.theme
        }
      },
      // 判断对话框展示/隐藏
      dialogVisible: false,
      LessondialogVisible: false
    }
  },
  methods: {
    async loadCourseSection () {
      const { data } = await getSectionAndLesson(this.courseId)
      if (data.code === '000000') {
        this.sections = data.data
      }
    },
    handleAllowDrop (draggingNode, dropNode, type) {
      // 1. 只能同级移动，type不能为 inner
      // 2. 课时不能移动到其他章节中
      console.log(draggingNode, dropNode, type)
      return type !== 'inner' && draggingNode.data.sectionId === dropNode.data.sectionId
    },
    async handleNodeDrop (draggingNode, dropNode, type, event) {
      // 拖拽完成请求接口更新数据
      // 可以使用Promise.all() 便于进行统一操作
      try {
        await Promise.all(dropNode.parent.childNodes.map((item, index) => {
          if (draggingNode.data.lessonDTOS) {
            return saveOrUpdateSection({
              id: item.data.id,
              orderNum: index
            })
          } else {
            return saveOrUpdateLesson({
              id: item.data.id,
              orderNum: index
            })
          }
        }))
        this.$message.success('数据更新成功！')
      } catch (err) {
        this.$message.success('数据更新失败', err)
      }
    },
    async handleAddSection () {
      // 添加阶段（章节）
      const { data } = await saveOrUpdateSection(this.sectionForm)
      console.log(data)
      if (data.code === '000000') {
        this.loadCourseSection(this.courseId)
        this.dialogVisible = false
        this.$message.success('添加阶段成功！')
      }
    },
    handleEditSection (data) {
      // 编辑章节，展示数据
      this.dialogVisible = true
      // 直接去节点的数据
      this.sectionForm = data
    },
    handleAddLesson (data) {
      // 显示添加课程弹框
      this.LessondialogVisible = true
      this.lessonForm.sectionName = data.sectionName
      this.lessonForm.sectionId = data.id
    },
    async handleSaveLesson () {
      // 保存课时
      const { data } = await saveOrUpdateLesson(this.lessonForm)
      if (data.code === '000000') {
        this.loadCourseSection(this.courseId)
        this.LessondialogVisible = false
        this.$message.success('添加课时成功！')
      }
    },
    handleEditLesson (data, node) {
      // 编辑课程，展示数据
      this.LessondialogVisible = true
      this.lessonForm = data
      // 获取父元素的 label 即 sectionName
      this.lessonForm.sectionName = node.parent.label
    }
  }
}

</script>
<style lang='scss' scoped>
.inner {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
::v-deep .el-tree-node__content {
  height: auto;
}
.el-card__header div{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
